package week13.kafka.producer;

import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author edward
 * @since 2021-09-21
 */
@SpringBootApplication
public class SpringBootApplicationProducer {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootApplicationProducer.class, args);
    }
    // implements ApplicationRunner
    /*@Override
    public void run(ApplicationArguments args) throws Exception {
    }
    */
    @Bean
    public ApplicationRunner runner(KafkaTemplate<String, String> template) throws Exception {
        return args -> {
            for (int i = 1; i <= 1000; i++) {
                template.send("demo", "Sent index=" + i);
            }
        };
    }

    @Bean
    public ProducerFactory<String, String> producerFactory() {
        return new DefaultKafkaProducerFactory<>(senderProps());
    }
    private Map<String, Object> senderProps() {
        Map<String, Object> props = new HashMap<>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9084,localhost:9083,localhost:9082,localhost:9081");
        props.put(ProducerConfig.LINGER_MS_CONFIG, 10);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        return props;
    }
    @Bean
    public KafkaTemplate<String, String> kafkaTemplate(ProducerFactory<String, String> producerFactory) {
        return new KafkaTemplate<>(producerFactory);
    }
}
